package com.ruoyi.web.controller.tool;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.doudou.minio.Minio;
import com.ruoyi.cert.domain.Cert;
import com.ruoyi.cert.service.ICertService;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@RestController
@RequestMapping("/test")
public class TestControl {

    @Autowired private ISysUserService service;

    @Autowired private Minio minio;

    @Autowired private ICertService certService;

    Set<String> names = new HashSet<>(1024);

    @GetMapping("/doudou")
    public Object doudou() throws Exception {
        File file = FileUtil.file("Z:\\jiayi\\postpartum\\images");

        for (File childFile : file.listFiles()) {
            names.add(getFileSimpleName(childFile));
        }

        List<SysUser> sysUsers = service.selectUserList(SysUser.builder().build());

        int count = 0;
        String nickName;
        String imageName;
        String url;
        File image;
        SysUser user;
        for (SysUser sysUser : sysUsers) {
            nickName = sysUser.getNickName();
            imageName = dou(nickName);
            if (StrUtil.isNotBlank(imageName)){
                image = FileUtil.file("Z:\\jiayi\\postpartum\\images\\" + imageName);
                url = minio.uploadFile(image);
                user = SysUser.builder().userId(sysUser.getUserId()).avatar(url).build();
                service.updateUser(user);
                count++;
            }
        }

        return count;
    }

    private String dou(String name){
        for (String imageName : names) {
            if (StrUtil.contains(imageName,name)){
                return imageName;
            }
        }
        return null;
    }

    private static String getFileSimpleName(File file){
        return  file.getName().replaceAll("[\\\\/]", "");
    }

    private static String getSimpleName(String fileName){
        String[] split = fileName.split("/");
        return split[split.length-1];
    }

    @GetMapping("/doudou2")
    public Object doudou2() throws Exception {
        List<Cert> certs = certService.selectCertList(Cert.builder().build());

        int count = 0;
        for (Cert cert : certs) {
            if (StrUtil.isNotBlank(cert.getCertImg())){
                String simpleName = getSimpleName(cert.getCertImg());
                System.out.println(simpleName);
                minio.delete(simpleName);
                count++;
            }
        }
        return count;
    }
}
